<?php

namespace app\msgapi\service;

use app\msgapi\model\{AdminUser, AuthGroup, OperateLog};
use app\utils\Http;
use thans\jwt\facade\JWTAuth;
use think\facade\Cache;

class HsloginService extends BaseService
{
    private AdminUser $adminUser;
    private OperateLog $operateLog;
    public function __construct(AdminUser $adminUser, OperateLog $operateLog)
    {
        parent::__construct();
        $this->adminUser = $adminUser;
        $this->operateLog = $operateLog;
    }

    /**账号登入
     * @param $username
     * @param $password
     * @return \think\response\Json
     */
    public function login($username, $password)
    {
        if(Cache::get("admin_$username") && (Cache::get("admin_$username") >= 5)) return error_json('密码错误超过5次,请五分钟后重试或联系管理员重置密码');
        $admin_user = $this->adminUser->where('username',$username)->findOrEmpty()->toArray();
        $ip = $this->request->ip(); $time = date('Y-m-d H:i:s');
        // 查不到、密码错误
        if (!$admin_user || !password_verify($password, $admin_user['password'])){
            $admin_user && HsoperateLogService::addLog(1,$admin_user['id'],'[账号]登入失败，用户名或者密码错误','');
            Cache::get("admin_$username") ? Cache::inc("admin_$username") : Cache::set("admin_$username",1,300); //缓存账号错误次数
            return error_json('用户名或者密码错误');
        }
        // 账号禁用
        if($admin_user['state'] != 1){
            HsoperateLogService::addLog(1,$admin_user['id'],'[账号]登入失败，当前用户已禁用','');
            return error_json('当前用户已禁用');
        }
        // 用户组禁用
        if(AuthGroup::where(['id'=>$admin_user['group_id']])->value('state') == 0){
            HsoperateLogService::addLog(1,$admin_user['id'],'[账号]登入失败，当前用户组已禁用','');
            return error_json('当前用户组已禁用');
        }
        $token = JWTAuth::builder(['adminid'=>$admin_user['id'],'admin_groupid'=>$admin_user['group_id']]);
        //todo..前台请求示例：header : { authorization : 'bearer $token' }

        // 登入信息
        $this->adminUser::update(['last_time'=>$time,'last_ip'=>$ip],['id'=>$admin_user['id']]);
        HsoperateLogService::addLog(1,$admin_user['id'],'[账号]登入成功','');

        return success_json('[账号]登入成功',['token'=>['token'=>$token,'exp'=>strtotime('+'.config('jwt.ttl').'seconds')]]);
    }

    /**扫码登入\单点登入
     * @return \think\response\Json
     * @throws \Throwable
     * @throws \app\utils\UtilsException
     */
    public function wxlogin($data)
    {
        $corpInfo = HscorpInfoService::getCorpInfo(env('wework.corpid'),true); //获取企业密钥信息
        $corpid = $corpInfo['corp_info']['corpid'];
        $agentid = $corpInfo['corp_info']['agent_id'];
        $secret = $corpInfo['corp_info']['agent_secret'];
        $code = $data['code'];
        $state = $data['state'];
        $http = new Http([]);
        if ($code && $state) {
            if(!$access_token = Cache::get('qywx_access_token')){
                $getTokenUrl = "gettoken?corpid=".$corpid."&corpsecret=".$secret;
                $accessTokenArr = $http->request('GET',$getTokenUrl);
//                    $accessTokenArr = json_decode($http->request('GET',$getTokenUrl),true);
                if ($accessTokenArr['errcode'] !== 0) {return error_json($accessTokenArr['errmsg']);}//获取时出现错误。code无效
                //存入accesstoken
                Cache::set('qywx_access_token', $accessTokenArr['access_token'], $accessTokenArr['expires_in']-200);
                $access_token = $accessTokenArr['access_token'];
            }
            $url = "user/getuserinfo?access_token=".$access_token."&code=".$code;
//                $res_user = json_decode(curl_get($url), true);
            $res_user = $http->request('GET',$url);
            if($res_user['errcode'] !== 0){return error_json($res_user['errmsg']);}
            $admin_user = AdminUser::where('userid',$res_user['UserId'])->findOrEmpty()->toArray();
            if(!$admin_user) return error_json('用户不存在');
            $ip = $this->request->ip(); $time = date('Y-m-d H:i:s');
            // 账号禁用
            if($admin_user['state'] != 1){
                HsoperateLogService::addLog(1,$admin_user['id'],'[扫码/单点登录]登入失败，当前用户已禁用','');
                return error_json('当前用户已禁用');
            }
            // 用户组禁用
            if(AuthGroup::where(['id'=>$admin_user['group_id']])->value('state') == 0){
                HsoperateLogService::addLog(1,$admin_user['id'],'[扫码/单点登录]登入失败，当前用户组已禁用','');
                return error_json('当前用户组已禁用');
            }
            $token = JWTAuth::builder(['adminid'=>$admin_user['id'],'admin_groupid'=>$admin_user['group_id']]);
            //前台请求示例：header : { authorization : 'bearer $token' }
            // 登入信息
            $this->adminUser::update(['last_time'=>$time,'last_ip'=>$ip],['id'=>$admin_user['id']]);
            HsoperateLogService::addLog(1,$admin_user['id'],'[扫码/单点登录]登入成功','');
            return success_json('[扫码/单点登录]登入成功',['token'=>['token'=>$token,'exp'=>strtotime('+'.config('jwt.ttl').'seconds')]]);
        } else {
            return success_json('获取企业id成功',['corpid'=>$corpid,'agentid'=>$agentid],1000);
        }
    }
}